$(function($) {
    // initMeasureColumnsFields("bus");

    initTab();
});
var measureProperty = {
    "yc": {
        datafields: [],
        columns: []
    },
    "yx": {
        datafields: [],
        columns: []
    },
    "yk": {
        datafields: [],
        columns: []
    },
    "yt": {
        datafields: [],
        columns: []
    }
};

//加载配置文件，并形成界面
function initGrid(measureType) {



    var url = "table_xml/Component/Measure/" + measureType + ".xml";
    // prepare the data
    var source =tableSource(url);
    var table = $('#measure_grid_' + measureType);
    /////////////////////////////////////
    //对AVC AGC 公共部分量测需要区分显示
    ///////////////////////////////////////
    var cellclass = function(row, columnfield, value, rowdata) {
            // if (value < 20) {
            //     return 'red';
            // } else if (value >= 20 && value < 50) {
            //     return 'yellow';
            // } else return 'green';
            //AVC 
            if (rowdata.DataSort) {
                if (rowdata.DataSort == 1) {
                    return 'AVC';
                }
                //AGC 
                else if (rowdata.DataSort == 2) {
                    return 'AGC';
                } else {
                    return 'AVC_AGC';

                }
            } else {

                return "red";
            }
        }
        //加载配置文件
    var dataAdapter = new $.jqx.dataAdapter(source, {
        autoBind: true,
        loadComplete: function() {
            // get data records.
            var records = dataAdapter.records;
            var length = records.length;
            for (var i = 0; i < length; i++) {
                var record = records[i];
                var fields = {};
                fields["name"] = record.Field;
                measureProperty[measureType].datafields.push(fields);

                var column = {};
                column["datafield"] = record.Field;
                column["text"] = record.Desc;
                column["cellclassname"] = cellclass;

                //根据 配置项的多少决定是否设置宽度
                var width = table.width();

                if ((length * 120) > width)
                    column["width"] = 120;


                if (record.DataType.indexOf("Bool") > -1) //直接判断== 也可以，为了防止字符串中的空格
                {

                    //	alert(record.DataType.indexOf("Bool"));
                    column["columntype"] ='checkbox'; //'custom'; // ;
                    column["threestatecheckbox"] = false;
                    column["width"] = 65;
                    column["cellsrenderer"] = function(row, datafield, value, defaultHtml, columnproperties, rowdata) {


                        // 不可编辑状态
                        var disabledStr = '<div tabindex="0" class="jqx-widget jqx-checkbox"   style=" width:100%;height:100%; position: absolute; cursor: auto; background-color:#303030">  </div>';

                        var useflg = table.jqxGrid('getcellvalue', row, "UseFlag");
                        if (useflg == false) {

                            editableFlag = false;

                        }
                        //当前量测是AVC量测，隐藏AGC的可编辑项
                        if (rowdata.DataSort == 1) {
                            if (datafield.indexOf("AGC") > -1)
                                return disabledStr;
                        }
                        //当前量测是AGC量测，隐藏AVC的可编辑项
                        else if (rowdata.DataSort == 2) {
                            if (datafield.indexOf("AVC") > -1)
                                return disabledStr;
                        }
                        //当前量测公共量测，隐藏AVC-AGC的可编辑项
                        else {
                            // if (datafield.indexOf("AGC")>-1 || datafield.indexOf("AVC")>-1)
                            //     return disabledStr;
                        }

                        //
                        // 编辑状态下，不同值，显示不同的状态
                        var checked = value ? ' class="jqx-checkbox-check-checked jqx-checkbox-check-checked-black"' : '';
                        var str = '<div   style="left: 50%; top: 50%; margin-top: -7px; margin-left: -10px; position: absolute; cursor: auto;"><div class="jqx-checkbox-default jqx-checkbox-default-black jqx-fill-state-normal jqx-fill-state-normal-black jqx-rc-all jqx-rc-all-black"><div style="width: 13px; height: 13px;"><span  ' + checked + 'style="width: 13px; height: 13px;"></span></div></div><div style="clear: both;"></div></div>';
                        return str;

                    };
                    column["initeditor"] = function(row, cellvalue, editor, celltext, cellwidth, cellheight) {
                        // editor.jqxCheckBox({width:cellwidth,height:cellheight,chekced:"true"});
                        editor.jqxCheckBox('val', cellvalue);
                    };
                    column["createeditor"] = function(row, cellvalue, editor, celltext, cellwidth, cellheight) {
                        // assign a new data source to the dropdownlist.

                        editor.jqxCheckBox({
                            width: cellwidth,
                            height: cellheight,
                            theme: theme
                        }).attr("style",'position: absolute; top: 50%; left: 50%; margin-top: 7px; margin-left: 10px; cursor: auto;');
                    };
                    column["geteditorvalue"] = function(row, cellvalue, editor) {
                        // return the editor's value.
                        return editor.jqxCheckBox('val');
                    };

                }
                ///////////////////////////////////////////////
                else {
                    column["cellsrenderer"] = function(row, datafield, value, defaultHtml, columnproperties, rowdata) {

                        //根据 column->feild column 判断当前列。
                        var editableFlag = true;
                        // 不可编辑状态
                        var disabledStr = '<div tabindex="0" class="jqx-widget jqx-checkbox"   style=" width:100%;height:100%; position: absolute; cursor: auto; background-color:#303030">  </div>';
                        //当前量测是AVC量测，隐藏AGC的可编辑项
                        if (rowdata.DataSort == 1) {
                            if ((datafield == "FlucVal")) {
                                editableFlag = table.jqxGrid('getcellvalue', row, "AVCFlucFlag");

                            }
                            if (datafield.indexOf("AGC") > -1)
                                return disabledStr;
                        }
                        //当前量测是AGC量测，隐藏AVC的可编辑项
                        else if (rowdata.DataSort == 2) {
                            if ((datafield == "FlucVal")) {
                                editableFlag = table.jqxGrid('getcellvalue', row, "AGCFlucFlag");

                            }
                            if (datafield.indexOf("AVC") > -1)
                                return disabledStr;
                        }
                        //当前量测公共量测,显示所有项
                        else {

                        }
                        // if (datafield.indexOf("AGC")>-1 || datafield.indexOf("AVC")>-1||datafield.indexOf("Fluc")>-1||datafield.indexOf("Limit")>-1)
                        //     return disabledStr;
                        if ((datafield == "FlucVal")) {
                            editableFlag = table.jqxGrid('getcellvalue', row, "AVCFlucFlag") || table.jqxGrid('getcellvalue', row, "AGCFlucFlag");

                        }

                        // }



                        var useflg = table.jqxGrid('getcellvalue', row, "UseFlag");
                        if (useflg == false) {

                            editableFlag = false;

                        } else if ((datafield == "FlucVal")) {
                            //  editableFlag = table.jqxGrid('getcellvalue', row, "FlucFlag");

                        }
                        ////
                        else if ((datafield == "ValidHigh") || (datafield == "ValidLow")) {

                            editableFlag = table.jqxGrid('getcellvalue', row, "ValidFlag");

                        }
                        // ////
                        // else if ((datafield == "LimitHigh") || (datafield == "LimitLow")) {

                        //     editableFlag = table.jqxGrid('getcellvalue', row, "LimitFlag");

                        // }
                        ////
                        else if ((datafield == "AVCReverseUp") || (datafield == "AVCReverseDown")) {
                            editableFlag = table.jqxGrid('getcellvalue', row, "AVCReverseFlag");

                        } else {

                        }

                        if (editableFlag == false) {


                            var element = $(defaultHtml);
                            element.css('color', '#131313');
                            return element[0].outerHTML;
                        }

                        return defaultHtml;

                    } //end cellsrenderer


                }
                column["cellbeginedit"] = function(row, datafield, value, defaultHtml, columnproperties, rowdata) {

                    //获取row对应的datafield的flag的ckeckbox，如果是1，返回true，如果是0，返回false
                    //如果量测启用，前面的所有项才可编辑
                    //这里只有遥测会有这样的配置约束，所以在这里直接填写了遥测dom的div对应的id。在这里取dom的owner的id。不太好弄
                    //波动 Fluc     --对应单元格返回false
                    //有效 Valid    --对应单元格返回false
                    //闭锁 Limit    --对应单元格返回false
                    //反调 Reverse  --对应单元格返回false
                    //启用 Use      --对应row  返回false

                    //  var field = record.Field;
                    //   var prefix = datafield.substr(0, datafield.indexOf("Flag"));
                    //启用列永远可以编辑。
                    if (datafield == 'UseFlag')
                        return true;
                    var editableFlag = true;

                    //根据 column->feild column 判断当前列。
                    var editableFlag = true;

                    ////
                    var useflg = table.jqxGrid('getcellvalue', row, "UseFlag");
                    if (useflg == false) {

                        editableFlag = false;

                    } else if ((datafield == "FlucVal")) {
                        editableFlag = table.jqxGrid('getcellvalue', row, "FlucFlag");

                    }
                    // ////
                    // else if ((datafield == "ValidHigh") || (datafield == "ValidLow")) {

                    //     editableFlag = table.jqxGrid('getcellvalue', row, "ValidFlag");

                    // }
                    // ////
                    // else if ((datafield == "LimitHigh") || (datafield == "LimitLow")) {

                    //     editableFlag = table.jqxGrid('getcellvalue', row, "LimitFlag");

                    // }
                    ////
                    else if ((datafield == "AVCReverseUp") || (datafield == "AVCReverseDown")) {
                        editableFlag = table.jqxGrid('getcellvalue', row, "AVCReverseFlag");

                    } else {

                    }

                    return editableFlag;

                } //end cellbeginedit
                //checkbox 相关的单元格，如果checkbox没有备选中，不允许编辑



                measureProperty[measureType].columns.push(column);
            }



            //================== 表格初始话数据加载完成了之后才初始化 tab，然后在tab的init中初始化表格
            //==加载表格数据  initTab(eqpType);
            function loadDATA(measureType) {

                var source = {
                    datatype: "csv",
                    datafields: measureProperty[measureType].datafields,
                    url: 'defaultData/component/measure/' + gPageParam.eqpType + '/' + measureType + '.csv'
                };

                var dataAdapter = new $.jqx.dataAdapter(source, {
                    async: false,
                    loadError: function(xhr, status, error) {
                        alert('Error loading "' + source.url + '" : ' + error);
                    }
                });

                var table = $("#measure_grid_" + measureType).jqxGrid({
                        width: '100%',
                        height: '99%',
                        theme: theme,
                        editable: true,
                        altrows: true,
                        source: dataAdapter,
                        editmode: "click",

                        enablebrowserselection: false, //禁止浏览器文本选择功能

                        selectionmode: 'multiplecellsadvanced', //'multiplecellsadvanced', //'multiplecellsextended' , //设置选择方式

                        columns: measureProperty[measureType].columns
                    })
                    .on("cellclick", function(event) {

                        table.jqxGrid('begincelledit', event.args.rowindex, event.args.datafield);

                    })
                    .on('cellvaluechanged', function(event) {
                        //{yc:{number:{"field":"value"},yx:{number:{"field":"value"}};
                        var column = args.datafield;
                        var row = args.rowindex;
                        var value = args.newvalue;
                        //将boolean转换为number类型
                        if (value.constructor == Boolean)
                            value = Number(value);

                        var oldvalue = args.oldvalue;
                        //设置变化值到缓存中
                        if (!$('#measure_tab').data("rowData"))
                            $('#measure_tab').data("rowData", {});
                        var rowData = $('#measure_tab').data("rowData");
                        if (!rowData[measureType])
                            rowData[measureType] = {};
                        if (!rowData[measureType][row])
                            rowData[measureType][row] = {};
                        if (!rowData[measureType][row][column])
                            rowData[measureType][row][column] = value;
                        // 
                        // $.extend(rowData[measureType]["fieldsData"],{column:value});
                        $('#measure_tab').data("rowData", rowData);


                        // console.dir(column + '==' + row + "===" + value + $(this).attr('id'));
                    });
            }
            loadDATA(measureType);
        }

    });



}

//初始化tab
function initTab(eqpType) {

    var initWidgets = function(tab) {
            //alert(tab);// 每个tab切换的时候，加载自己需要的数据
            switch (tab) {
                case 0:
                    initGrid("yc");
                    break;
                case 1:
                    initGrid("yx");
                    break;
                case 2:
                    initGrid("yk");
                    break;
                case 3:
                    initGrid("yt");
                    break;
            }
        }
        //	$('#measure_tab_layout').hide();	
    $('#measure_tab').on('created', function() {
        //alert("OK");		
        $('#measure_tab_layout').show();
    });
    $('#measure_tab').jqxTabs({
        width: '99.5%',
        height: '600',
        theme: theme,
        initTabContent: initWidgets

    })



}